<?php

namespace Database\Seeders;

use App\Models\Comment;
use App\Models\Post;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class CommentSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $posts = Post::published()->get();
        $users = User::all();

        if ($posts->isEmpty()) {
            $this->command->warn('没有已发布的文章，跳过评论创建');
            return;
        }

        if ($users->isEmpty()) {
            $this->command->warn('没有用户，跳过评论创建');
            return;
        }

        // 只选择1-2篇文章来创建评论
        $targetPosts = $posts->random(min(2, $posts->count()));
        
        $this->command->info('创建评论（集中在 ' . $targetPosts->count() . ' 篇文章中）...');
        $comments = collect();

        // 只为选定的文章创建评论
        foreach ($targetPosts as $post) {
            $this->command->line("  - 为文章「{$post->title}」创建评论...");
            
            // 创建主评论（每篇文章3-5条）
            $mainCommentCount = rand(3, 5);
            $mainComments = Comment::factory($mainCommentCount)
                ->create()
                ->each(function ($comment) use ($post, $users) {
                    $comment->post()->associate($post);
                    $comment->user()->associate($users->random());
                    $comment->save();
                });

            $comments = $comments->merge($mainComments);
            $this->command->line("    创建了 {$mainCommentCount} 条主评论");

            // 为部分主评论创建回复（每篇文章1-3条回复）
            $replyCount = rand(1, 3);
            $commentsToReply = $mainComments->random(min($replyCount, $mainComments->count()));
            
            foreach ($commentsToReply as $mainComment) {
                $replies = Comment::factory(1)
                    ->create()
                    ->each(function ($reply) use ($post, $users, $mainComment) {
                        $reply->post()->associate($post);
                        $reply->user()->associate($users->random());
                        $reply->parent_id = $mainComment->id;
                        $reply->save();
                    });

                $comments = $comments->merge($replies);
            }
            
            if ($replyCount > 0) {
                $this->command->line("    创建了 {$replyCount} 条回复");
            }
        }

        // 批量更新评论统计
        $this->command->info('更新评论统计...');
        $postCounts = $comments->groupBy('post_id')
            ->map->count()
            ->toArray();

        foreach ($postCounts as $postId => $count) {
            DB::table('posts')
                ->where('id', $postId)
                ->update(['comment_count' => $count]);
            $this->command->line("  - 文章 ID {$postId} 有 {$count} 条评论");
        }

        // 创建一些热门评论（减少点赞数量）
        if ($comments->isNotEmpty()) {
            $this->command->info('创建热门评论...');
            $popularCommentCount = min(3, $comments->count());
            $popularComments = $comments->random($popularCommentCount);
            
            foreach ($popularComments as $comment) {
                $likeCount = rand(2, 5); // 减少点赞数量
                $likeUsers = $users->random(min($likeCount, $users->count()));
                $comment->likes()->attach($likeUsers);
            }
            $this->command->line("  - 为 {$popularCommentCount} 条评论添加了点赞");
        }

        $this->command->info('评论创建完成！共创建 ' . $comments->count() . ' 条评论');
    }
} 